Telegram Group & Telegram Channel
Каждый вызов next(x) возвращает следующее значение из итератора x, если только не возникает исключение. Если это StopIteration, значит, итератор исчерпан и больше не может возвращать значения. При итерации по генератору это исключение выбрасывается автоматически в конце его тела:


>>> def one_two():
... yield 1
... yield 2
...
>>> i = one_two()
>>> next(i)
1
>>> next(i)
2
>>> next(i)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration


StopIteration автоматически обрабатывается инструментами, которые вызывают next за вас:


>>> list(one_two())
[1, 2]


Проблема в том, что любое неожиданное StopIteration, возникшее внутри генератора, приводит к его молчаливому завершению, а не к выбросу исключения:


def one_two():
yield 1
yield 2

def one_two_repeat(n):
for _ in range(n):
i = one_two()
yield next(i)
yield next(i)
yield next(i)

print(list(one_two_repeat(3)))


Последний yield здесь — ошибка: StopIteration вызывается и прерывает list(...). В результате получаем [1, 2], что может удивить.

Однако это поведение было изменено в Python 3.7. Теперь любое внешнее StopIteration, возникшее в генераторе, преобразуется в RuntimeError:


Traceback (most recent call last):
File "test.py", line 10, in one_two_repeat
yield next(i)
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "test.py", line 12, in <module>
print(list(one_two_repeat(3)))
RuntimeError: generator raised StopIteration


Такое же поведение можно включить начиная с Python 3.5 с помощью:


from __future__ import generator_stop


👉@BookPython



tg-me.com/BookPython/3628
Create:
Last Update:

Каждый вызов next(x) возвращает следующее значение из итератора x, если только не возникает исключение. Если это StopIteration, значит, итератор исчерпан и больше не может возвращать значения. При итерации по генератору это исключение выбрасывается автоматически в конце его тела:


>>> def one_two():
... yield 1
... yield 2
...
>>> i = one_two()
>>> next(i)
1
>>> next(i)
2
>>> next(i)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration


StopIteration автоматически обрабатывается инструментами, которые вызывают next за вас:


>>> list(one_two())
[1, 2]


Проблема в том, что любое неожиданное StopIteration, возникшее внутри генератора, приводит к его молчаливому завершению, а не к выбросу исключения:


def one_two():
yield 1
yield 2

def one_two_repeat(n):
for _ in range(n):
i = one_two()
yield next(i)
yield next(i)
yield next(i)

print(list(one_two_repeat(3)))


Последний yield здесь — ошибка: StopIteration вызывается и прерывает list(...). В результате получаем [1, 2], что может удивить.

Однако это поведение было изменено в Python 3.7. Теперь любое внешнее StopIteration, возникшее в генераторе, преобразуется в RuntimeError:


Traceback (most recent call last):
File "test.py", line 10, in one_two_repeat
yield next(i)
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "test.py", line 12, in <module>
print(list(one_two_repeat(3)))
RuntimeError: generator raised StopIteration


Такое же поведение можно включить начиная с Python 3.5 с помощью:


from __future__ import generator_stop


👉@BookPython

BY Библиотека Python разработчика | Книги по питону


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/BookPython/3628

View MORE
Open in Telegram


Библиотека Python разработчика Telegram | DID YOU KNOW?

Date: |

The S&P 500 slumped 1.8% on Monday and Tuesday, thanks to China Evergrande, the Chinese property company that looks like it is ready to default on its more-than $300 billion in debt. Cries of the next Lehman Brothers—or maybe the next Silverado?—echoed through the canyons of Wall Street as investors prepared for the worst.

Should I buy bitcoin?

“To the extent it is used I fear it’s often for illicit finance. It’s an extremely inefficient way of conducting transactions, and the amount of energy that’s consumed in processing those transactions is staggering,” the former Fed chairwoman said. Yellen’s comments have been cited as a reason for bitcoin’s recent losses. However, Yellen’s assessment of bitcoin as a inefficient medium of exchange is an important point and one that has already been raised in the past by bitcoin bulls. Using a volatile asset in exchange for goods and services makes little sense if the asset can tumble 10% in a day, or surge 80% over the course of a two months as bitcoin has done in 2021, critics argue. To put a finer point on it, over the past 12 months bitcoin has registered 8 corrections, defined as a decline from a recent peak of at least 10% but not more than 20%, and two bear markets, which are defined as falls of 20% or more, according to Dow Jones Market Data.

Библиотека Python разработчика from id


Telegram Библиотека Python разработчика | Книги по питону
FROM USA